package com.java.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @author jl
 * Created on 2020/9/29
 * 自定义handler要继承ChannelInboundHandlerAdapter
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<StudentPOJO.Student> {

    /**
     * 读取数据事件
     *
     * @param ctx 上下文对象,含义pipeline,channel,地址
     * @param student 客户端发送的数据
     */
    @Override
    public void channelRead0(ChannelHandlerContext ctx, StudentPOJO.Student student) throws Exception {
        // 读取从客户端发送来的StudentPOJO.Student对象
        System.out.println("客户端发送的消息是:" + student.getId()+" "+student.getName());
        System.out.println("客户端地址是:" + ctx.channel().remoteAddress());
    }

    // 数据读取完毕
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ByteBuf byteBuf = Unpooled.copiedBuffer("Hello client 000", CharsetUtil.UTF_8);
        ctx.writeAndFlush(byteBuf);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 发生异常关闭channel
        ctx.channel().close();
    }

}
